from appium.webdriver.common.appiumby import AppiumBy
from selenium.common import NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait


class OperateUtil:

    def __init__(self, driver):
        self.driver = driver

    # Xpath定位
    def find_xpath(self, xpath, timeout):
        """
        :param xpath: xpath表达式
        :param timeout: 超时时间
        :return: element
        """
        try:
            WebDriverWait(self.driver, timeout).until(lambda driver: driver.find_element(AppiumBy.XPATH, f"{xpath}"))
            element = self.driver.find_element(AppiumBy.XPATH, f"{xpath}")
            return element
        except NoSuchElementException:
            print("超时为获取到元素")
            return None

    # 滚动查找
    def find_roll(self, text):
        try:
            element = self.driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, f'new UiScrollable(new UiSelector().scrollable(true).instance(0))'
                                                                             f'.scrollIntoView(new UiSelector().text("{text}").instance(0));')
            return element
        except NoSuchElementException:
            print('未找到:' + '%s' % text)
            return None
